package com.jeesite.modules.wx.service.serviceImpl;

import com.alibaba.fastjson.JSONObject;
import com.jeesite.modules.common.PostUtils;
import com.jeesite.modules.common.refun.StringUtil;
import com.jeesite.modules.wx.entity.WxUser;
import com.jeesite.modules.wx.service.WxLoginService;
import com.jeesite.modules.wx.service.WxUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author wangjianxin
 */
@Service
@Slf4j
public class WxLoginServiceImpl implements WxLoginService {

    @Autowired
    private WxUserService wxUserService;

    /**
     */
    private static String AppID = "wxc86ac9d5537decf6";
    private static String AppSecret = "55ef33c909863b6fb1a1d27adca79f66";
    private static String redirectUrl = "http://api.wangjianxin.top/wx/redirect";
//
//    private static String AppID = "wxed8f98b6928194c2";
//    private static String AppSecret = "5b958c7eb7d20d0e4fce509046186c77";
//    private static String redirectUrl = "http://01a4dd7a.ngrok.io//wx/redirect";

    @Override
    public String getOAuthRedirectUrl(String activityId,String inviteOpenId,String userOpenId) {

        log.info("getOAuthRedirectUrl AppID = {}", AppID);
        log.info("getOAuthRedirectUrl AppSecret = {}", AppSecret);
        log.info("getOAuthRedirectUrl redirectUrl = {}", redirectUrl);

        String state = activityId;
        if(StringUtils.isNotEmpty(inviteOpenId) && !inviteOpenId.equals("99")){
            state = activityId+","+ inviteOpenId;
        }
        if(StringUtil.isNotEmpty(userOpenId)){
            state += ","+userOpenId;
        }

        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+AppID+"" +
                "&redirect_uri="+redirectUrl+"&response_type=code&scope=snsapi_userinfo&state="+state+"#wechat_redirect";
        log.info("getOAuthRedirectUrl resultUrl = {}", url);

        return url;
    }

    @Override
    public JSONObject redirect(String code, String state) {
        log.info("授权登录后的回调地址");


        //来源授权登陆
        String getAccessTokenByCodeUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+AppID+"" +
                "&secret="+AppSecret+"&code="+code+"&grant_type=authorization_code ";
        String getAccessTokenByCodeResult = PostUtils.getToUrl(getAccessTokenByCodeUrl);
        log.info("getAccessTokenByCodeResult={}",getAccessTokenByCodeResult);

        JSONObject paredResut = (JSONObject) JSONObject.parse(getAccessTokenByCodeResult);
        log.info("redirectUrl getAccessTokenByCodeResult = {}", getAccessTokenByCodeResult);
        String access_token = (String) paredResut.get("access_token");
        if(StringUtils.isNotEmpty(access_token)){
            log.info("redirectUrl access_token = {}", access_token);
            String openid = (String) paredResut.get("openid");
            log.info("获得openId={}",openid);

            //save 保存或者更新,存在更新保存微信用户详细信息
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject = getUserinfo(access_token,openid);

            }catch (Exception e){
                e.printStackTrace();
                log.error("回调更新保存用户失败={}",e.getMessage());
            }

            return jsonObject;
        }

        return null;
    }

    /**
     * 根据access_token和openid获取微信用户详细信息，
     * 并且保存起来
     */
    @Override
    public JSONObject getUserinfo(String accessToken,String openid){

        String getUserinfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+accessToken+"&openid="+openid+"&lang=zh_CN";
        log.info("根据access_token和openid获取微信用户详细信息,getUserinfoUrl={}",getUserinfoUrl);
        String getUserinfoResult = PostUtils.getToUrl(getUserinfoUrl);
        log.info("根据access_token和openid获取微信用户详细信息,getUserinfoResult={}",getUserinfoResult);
        JSONObject result = new JSONObject();
        result.put("openid",openid);
        JSONObject userinfo = JSONObject.parseObject(getUserinfoResult);
        
        //将opined等信息存入数据库
        String thisOpenid = (String)userinfo.get("openid");
        String nickname = (String) userinfo.get("nickname");
        Integer sex = (Integer)userinfo.get("sex");
        String headimgurl = (String)userinfo.get("headimgurl");
        String city = (String)userinfo.get("city");

        log.info(" get weixn headimgurl = {}",headimgurl);
        log.info(" get weixn thisOpenid = {}",thisOpenid);
        log.info(" get weixn sex = {}",sex);
        log.info(" get weixn nickname = {}",nickname);
        log.info(" get weixn city = {}",city);

        //保存更新用户
        WxUser wxUser = new WxUser();
        wxUser.setWxOpenId(thisOpenid);
        List<WxUser> userList = wxUserService.findList(wxUser);
//        WxUser getTemp = wxUserService.get(wxUser);


        try {
            if(CollectionUtils.isNotEmpty(userList)){
//            if(null != getTemp){
                //更新头像+昵称
                WxUser updateTemp = userList.get(0);
                updateTemp.setNickName(nickname);
                updateTemp.setHeadImg(headimgurl);
                wxUserService.update(updateTemp);

                log.info("更新用户信息成功");
                return result;
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("更新用户信息失败={}",e.getMessage());
        }

        try {

            log.info("新用户={}昵称={}需要插入数据",thisOpenid,nickname);
            WxUser saveTemp = new WxUser();
            saveTemp.setWxOpenId(thisOpenid);
            saveTemp.setNickName(nickname);
            saveTemp.setUserName(nickname);
            saveTemp.setSex(sex.longValue());
            saveTemp.setCity(city);
            saveTemp.setHeadImg(headimgurl);

            wxUserService.insert(saveTemp);
        }catch (Exception e){
            e.printStackTrace();
            log.error("插入用户信息失败={}",e.getMessage());
        }


        log.info("插入用户信息成功");
        return result;
    }


}
